package cn.jhc.service;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import cn.jhc.dao.Dao;
import cn.jhc.entity.Article;

@WebServlet("/safe/addArticle.do")
@MultipartConfig(maxFileSize = 5368709120L)
public class AddArticleService extends HttpServlet {

    private static final Pattern FILE_PATTERN = Pattern.compile("filename=\"([^\"]*)\"");
    private static final Pattern FILE_SUFFIX_PATTERN = Pattern.compile("filename=\"[^\"]*(.[\\w]+)\"");
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // int id = Integer.parseInt(req.getParameter("id"));
        int id = 1;
        String idd = "ccc";
        String content = "";
        String username = "";
        


        for (Part part : req.getParts()) {
            if (part.getName().equals("id")) {
                username = extractString(part);
                try {
                    id = new Dao().getId(username);
                    System.out.println("uuu" + username);
                 } catch (SQLException e1) {
                     // TODO Auto-generated catch block
                     e1.printStackTrace();
                 }
                
            } else if (part.getName().equals("content")) {
                content = extractString(part);
            }
            // else if (part.getName().equals("")) {
            //     hobbies += extractString(part);
            // }
        }
        try {
            username = new Dao().getName(id);
            System.out.println("uuu" + username);
         } catch (SQLException e1) {
             // TODO Auto-generated catch block
             e1.printStackTrace();
         }
        System.out.println(content);

        String prefix = req.getServletContext().getRealPath("/uploads");
        Part filePart = req.getPart("image");
        String ctype = filePart.getHeader("Content-Type");
        String oriFilename = extractFilename(filePart.getHeader("Content-Disposition"));
        // String reFilename = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss").format(new Date()) + "-" + oriFilename;
        String reFilename = UUID.randomUUID().toString() + oriFilename;
        InputStream partInput = filePart.getInputStream();
        File destFile = new File(prefix + File.separator + reFilename);
        System.out.println(prefix);
        
        byte[] buffer = new byte[1024];
        FileOutputStream out = new FileOutputStream(destFile);
        int len = 0;
        while ((len = partInput.read(buffer)) != -1) {
            out.write(buffer);
        }




        Article article = new Article();
        article.setId(id);
        article.setContent(content);
        article.setReFilename(reFilename);

        try {
            new Dao().addArticle(article);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        resp.sendRedirect("/index.html?username=" + username);


    }
    private String extractFilename(String disposition) {
        String filename = "not_found";
        Matcher matcher = FILE_PATTERN.matcher(disposition);
        if (matcher.find()) {
            filename = matcher.group(1);
        }
        return filename;
    }
    
    private String extractString(Part part) {
        String result = "";
        try {
            InputStream in = part.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = reader.readLine();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
}
